#include "config.h" //通用配置头文件
#include "isr.h"
#define __SYSTICK
// #define EXTI
#define __TIMER
#define __UART
#define __ADC
#ifdef __SYSTICK

// uint16_t debug[16];
// SysTick interrupt handler - called every 1 ms (configured by SysConfig)
void SysTick_Handler(void)
{
	msTicks++;
}
#endif

#ifdef __EXTI
/*
 * Group1 IRQ handler handles GPIOA interrupts among others.
 * SysConfig enabled PA7 (GPIOA pin 7) as falling edge interrupt.
 */
void GROUP1_IRQHandler(void)
{
	/* Check if GPIOA PA7 triggered (enabled interrupt status) */
	if (DL_GPIO_getEnabledInterruptStatus(ENCODER_PORT, ENCODER_EC11_KEY_PIN) & ENCODER_EC11_KEY_PIN)
	{
		/* Clear the interrupt flag for PA7 */
		DL_GPIO_clearInterruptStatus(ENCODER_PORT, ENCODER_EC11_KEY_PIN);
		/* Set a flag for the main loop or other tasks to process */
		encoderEvent = 1;
	}

	/* If other Group1 sources exist, optionally check/clear them here.
	 * DL_Interrupt_getStatusGroup and DL_Interrupt_clearGroup can be used
	 * for group-level handling if needed.
	 */
}

#endif

#ifdef __TIMER

void TIMER_0_INST_IRQHandler(void)
{
	uint8_t raw[2];
	/* Check if TIER_0_INST update interrupt is pending */
	switch (DL_Timer_getPendingInterrupt(TIMER_0_INST))
	{
	case DL_TIMERG_IIDX_ZERO:
		/* 按键扫描 */
		// 原始按键读取：0 = 按下，1 = 释放
		raw[0] = (DL_GPIO_readPins(KEY_GRP_PORT, KEY_GRP_KEY_1_PIN) & KEY_GRP_KEY_1_PIN) ? 1 : 0;
		// raw[1] = (DL_GPIO_readPins(KEY_GRP_PORT, KEY_GRP_KEY_2_PIN) & KEY_GRP_KEY_2_PIN) ? 1 : 0;
		// 8-bit 移位寄存器消抖（每1ms采样一次 8ms 为一个窗口）
		static uint8_t key_hist[2] = {0xFF, 0xFF};
		static uint8_t key_stable[2] = {1, 1}; // 1 表示稳定，初始状态为稳定释放

		key_hist[0] = (uint8_t)((key_hist[0] << 1) | raw[0]);

		if (key_hist[0] == 0x00 && key_stable[0] != 0)
		{
			key_stable[0] = 0;
			keyPressEvent[0] = 1; // 稳定按下事件
		}
		else if (key_hist[0] == 0xFF && key_stable[0] != 1)
		{
			key_stable[0] = 1;
			// 可设置释放事件（如需）
		}
		// key_hist[1] = (uint8_t)((key_hist[1] << 1) | raw[1]);

		// if (key_hist[1] == 0x00 && key_stable[1] != 0)
		// {
		// 	key_stable[1] = 0;
		// 	keyPressEvent[1] = 1; // 稳定按下事件
		// }
		// else if (key_hist[1] == 0xFF && key_stable[1] != 1)
		// {
		// 	key_stable[1] = 1;
		// 	// 可设置释放事件（如需）
		// }
		/* 显示刷新 */
		LED4x4_Display();
		break;

	default:
		break;
	}
}

#endif

#ifdef __UART
volatile bool gUartDMARXdone = false; // DMA接收完成标志
volatile bool gUartDMATXdone = true;  // DMA发送完成标志
void UART_0_INST_IRQHandler(void)
{
	// Check if RX interrupt is pending
	switch (DL_UART_getPendingInterrupt(UART_0_INST))
	{
	case DL_UART_IIDX_DMA_DONE_RX:
		// DMA接收完成
		DL_DMA_disableChannel(DMA, DMA_CH0_CHAN_ID);
		DL_DMA_disableChannel(DMA, DMA_CH1_CHAN_ID);
		
		// 检查是否有残留数据（防止紧跟在 DMA 后的脏数据）
		// 如果 FIFO 非空，清空所有残留字节
		while (DL_UART_isRXFIFOEmpty(UART_0_INST) == false)
		{
			DL_UART_receiveData(UART_0_INST); // 丢弃残留数据
		}
		
		gUartDMARXdone = true; // 标记接收完成
		break;
	case DL_UART_IIDX_DMA_DONE_TX:
		// DMA发送完成，构造新帧准备下次传输
		DL_DMA_disableChannel(DMA, DMA_CH1_CHAN_ID);
		gUartDMATXdone = true;
		break;
	case DL_UART_IIDX_RX_TIMEOUT_ERROR:
		// 接收超时，清空FIFO并重新对齐DMA
		DL_DMA_disableChannel(DMA, DMA_CH0_CHAN_ID);
		
		// 清空UART RX FIFO（读取所有残留数据直到FIFO为空）
		while (DL_UART_isRXFIFOEmpty(UART_0_INST) == false)
		{
			DL_UART_receiveData(UART_0_INST); // 丢弃数据
		}
		
		// 重新设置DMA接收通道（从缓冲区起始位置重新对齐）
		DL_DMA_setSrcAddr(DMA, DMA_CH0_CHAN_ID, (uint32_t)(&UART_0_INST->RXDATA));
		DL_DMA_setDestAddr(DMA, DMA_CH0_CHAN_ID, (uint32_t)&gReceiveBuffer);
		DL_DMA_setTransferSize(DMA, DMA_CH0_CHAN_ID, sizeof(gReceiveBuffer));
		
		// 重新启用DMA接收通道
		DL_DMA_enableChannel(DMA, DMA_CH0_CHAN_ID);
		break;
	default:
		break;
	}
}
#endif

#ifdef __ADC
void ADC12_0_INST_IRQHandler(void)
{
	switch (DL_ADC12_getPendingInterrupt(ADC12_0_INST))
	{
	case DL_ADC12_IIDX_MEM7_RESULT_LOADED:
		// 读取ADC结果
		sensor_data.raw[9] = DL_ADC12_getMemResult(ADC12_0_INST, ADC12_0_ADCMEM_0);
		sensor_data.raw[10] = DL_ADC12_getMemResult(ADC12_0_INST, ADC12_0_ADCMEM_1);
		sensor_data.raw[11] = DL_ADC12_getMemResult(ADC12_0_INST, ADC12_0_ADCMEM_2);
		sensor_data.raw[12] = DL_ADC12_getMemResult(ADC12_0_INST, ADC12_0_ADCMEM_3);
		sensor_data.raw[8] = DL_ADC12_getMemResult(ADC12_0_INST, ADC12_0_ADCMEM_4);
		sensor_data.raw[13] = DL_ADC12_getMemResult(ADC12_0_INST, ADC12_0_ADCMEM_5);
		sensor_data.raw[14] = DL_ADC12_getMemResult(ADC12_0_INST, ADC12_0_ADCMEM_6);
		sensor_data.raw[15] = DL_ADC12_getMemResult(ADC12_0_INST, ADC12_0_ADCMEM_7);
		sensor_data.data_ready[0] = true; // 设置数据准备就绪标志
		break;

	default:
		break;
	}
}

void ADC12_1_INST_IRQHandler(void)
{
	switch (DL_ADC12_getPendingInterrupt(ADC12_1_INST))
	{
	case DL_ADC12_IIDX_MEM7_RESULT_LOADED:
		// 读取ADC结果
		sensor_data.raw[7] = DL_ADC12_getMemResult(ADC12_1_INST, ADC12_1_ADCMEM_0);
		sensor_data.raw[6] = DL_ADC12_getMemResult(ADC12_1_INST, ADC12_1_ADCMEM_1);
		sensor_data.raw[5] = DL_ADC12_getMemResult(ADC12_1_INST, ADC12_1_ADCMEM_2);
		sensor_data.raw[4] = DL_ADC12_getMemResult(ADC12_1_INST, ADC12_1_ADCMEM_3);
		sensor_data.raw[3] = DL_ADC12_getMemResult(ADC12_1_INST, ADC12_1_ADCMEM_4);
		sensor_data.raw[2] = DL_ADC12_getMemResult(ADC12_1_INST, ADC12_1_ADCMEM_5);
		sensor_data.raw[1] = DL_ADC12_getMemResult(ADC12_1_INST, ADC12_1_ADCMEM_6);
		sensor_data.raw[0] = DL_ADC12_getMemResult(ADC12_1_INST, ADC12_1_ADCMEM_7);
		sensor_data.data_ready[1] = true; // 设置数据准备就绪标志
		break;

	default:
		break;
	}
}
#endif